<?php

namespace App\Tasks;

use Throwable;
use App\Models\User;
use App\Models\Packet;
use App\Support\Currency;
use Illuminate\Support\Arr;
use App\Traits\RedPacketPush;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\ConfigYecsStaticRatio;

/**
 * 静态释放
 *
 * Class UserLevel
 * @package App\Tasks
 */
class YecsStaticRelease
{
    use RedPacketPush;

    public function __invoke()
    {
        // scale_id 待确认
        $configs = ConfigYecsStaticRatio::get()->keyBy('scale_id')->toArray();
        User::get()->each(function (User $user) use ($configs) {

            if ($user->admin_level) {
                $level = $user->admin_level;
            } else {
                $level = $user->level;
            }

            if (!Arr::has($configs, $level)) {
                return;
            }

            $config = $configs[$level];

            $released = Packet::where('user_id', $user->id)
                ->where('currency', Currency::YEC)->sum('value');

            if ($user->total_yecs == 0) {
                $ratio = 0;
            } else {
                $ratio = $released / $user->total_yecs;
            }

            if ($ratio < 0.2) {
                $value = $user->yecs * $config['yecs_one'];
            } else if ($ratio < 0.4) {
                $value = $user->yecs * $config['yecs_two'];
            } else if ($ratio < 0.6) {
                $value = $user->yecs * $config['yecs_three'];
            } else if ($ratio < 0.8) {
                $value = $user->yecs * $config['yecs_four'];
            } else {
                $value = $user->yecs * $config['yecs_five'];
            }

            //$value = big_number($value,5)->divide('100');
			$value = bcdiv($value,100,5);
            if ($value > 0) {
                try {
                    DB::transaction(function () use ($value, $user) {
                        $packet = Packet::create([
                            'value' => $value,
                            'user_id' => $user->id,
                            'type' => Packet::TYPE_DAY,
                            'currency' => Currency::YEC,
                            'expired_at' => now()->addHour(24)->toDateTimeString()
                        ]);

                        $packet->record()->create([
                            'value' => -$value,
                            'type' => '释放至 YEC',
                            'user_id' => $user->id,
                            'currency' => Currency::YECS
                        ]);
                      //  $this->send($packet);
                    });
                } catch (Throwable $exception) {
                    Log::error('yecs static release error: ' . $exception->getMessage());
                }
            }
        });
    }
}
